package com.jacob.cloud.mall.categoryproduct.controller;

import com.github.pagehelper.PageInfo;
import com.jacob.cloud.mall.categoryproduct.common.ProductConstant;
import com.jacob.cloud.mall.categoryproduct.model.pojo.Product;
import com.jacob.cloud.mall.categoryproduct.model.request.AddProductReq;
import com.jacob.cloud.mall.categoryproduct.model.request.ProductListReq;
import com.jacob.cloud.mall.categoryproduct.model.request.UpdateProductReq;
import com.jacob.cloud.mall.categoryproduct.service.IProductService;
import com.jacob.cloud.mall.common.common.ApiRestResponse;
import com.jacob.cloud.mall.common.common.Constant;
import com.jacob.cloud.mall.common.exception.MallException;
import com.jacob.cloud.mall.common.exception.MallExceptionEnum;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.UUID;

/**
 * 商品模块
 */
@RestController
public class ProductController {

    @Autowired
    private IProductService productService;

    @Value("${file.upload.ip}")
    private String ip;

    @Value("${file.upload.port}")
    private Integer port;

    @ApiOperation("新增商品")
    @PostMapping("/admin/product/add")
    public ApiRestResponse<Object> addProduct(@Valid @RequestBody AddProductReq addProductReq) {
        productService.add(addProductReq);
        return ApiRestResponse.success();
    }

    @ApiOperation("上传文件")
    @PostMapping("/admin/upload/file")
    public ApiRestResponse<Object> upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        // 获取文件扩展名
        String filename = file.getOriginalFilename();
        String suffix = null;
        if (filename != null) {
            suffix = filename.substring(filename.lastIndexOf("."));
        }

        // 组织新文件名
        UUID uuid = UUID.randomUUID();
        String newFileName = uuid + suffix;
        File destFile = null;

        // 文件保存到指定目录
        File fileDirectory = new File(ProductConstant.FILE_UPLOAD_DIR);
        destFile = new File(ProductConstant.FILE_UPLOAD_DIR + newFileName);
        if (!fileDirectory.exists()) {
            if (!fileDirectory.mkdir()) {
                throw new MallException(MallExceptionEnum.MKDIR_FAIL);
            }
        }

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            return ApiRestResponse.success(getHost(new URI(request.getRequestURL() + "")) + "/category-product/images/" + newFileName);
        } catch (URISyntaxException e) {
            return ApiRestResponse.error(MallExceptionEnum.UPLOAD_FAIL);
        }
    }

    @ApiOperation("更新商品")
    @PostMapping("/admin/product/update")
    public ApiRestResponse<Object> updateProduct(@Valid @RequestBody UpdateProductReq updateProductReq) {
        productService.update(updateProductReq);
        return ApiRestResponse.success();
    }

    @ApiOperation("删除商品")
    @PostMapping("/admin/product/delete")
    public ApiRestResponse<Object> deleteProduct(@RequestParam("id") Integer productId) {
        productService.delete(productId);
        return ApiRestResponse.success();
    }

    @ApiOperation("批量上下架")
    @PostMapping("/admin/product/batchUpdateSellStatus")
    public ApiRestResponse<Object> batchUpdateSellStatus(@RequestParam("ids") Integer[] ids, @RequestParam Integer sellStatus) {
        productService.batchUpdateSellStatus(ids, sellStatus);
        return ApiRestResponse.success();
    }

    @ApiOperation("后台商品列表")
    @GetMapping("/admin/product/list")
    public ApiRestResponse<PageInfo<Product>> listForAdmin(Integer pageSize, Integer pageNum) {
        PageInfo<Product> pageInfo = productService.listForAdmin(pageSize, pageNum);
        return ApiRestResponse.success(pageInfo);
    }

    @ApiOperation("前台商品列表")
    @GetMapping("/product/list")
    public ApiRestResponse<PageInfo<Product>> listForCustomer(ProductListReq productListReq) {
        PageInfo<Product> productPageInfo = productService.listForCustomer(productListReq);
        return ApiRestResponse.success(productPageInfo);
    }

    @ApiOperation("商品详情")
    @GetMapping("/product/detail")
    public ApiRestResponse<Product> detail(@RequestParam Integer id) {
        Product product = productService.detail(id);
        return ApiRestResponse.success(product);
    }

    @ApiOperation("商品详情（对内接口）")
    @GetMapping("/product/detailForFeign")
    public Product detailForFeign(@RequestParam Integer id) {
        Product product = productService.detail(id);
        return product;
    }

    @ApiOperation("商品扣库存（对内接口）")
    @PostMapping("/product/updateStock")
    public void updateStock(@RequestParam Integer productId, @RequestParam Integer stock){
        productService.updateStock(productId, stock);
    }

    private URI getHost(URI uri) {
        URI effectiveURI;
        try {
            effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), ip, port, null, null, null);
        } catch (URISyntaxException e) {
            e.printStackTrace();
            effectiveURI = null;
        }
        return effectiveURI;
    }

}
